package nonfixcycle

import (
	"blockchain/public/function"
	"bytes"
	"crypto/sha256"
	"encoding/json"
	"fmt"
)

type commit1Message struct {
	tradeHash [32]byte
}

func commit1(nodeSeq int,prepare2Verified *[K]prepare2Message,round int)(commit1Message){
	var h [32]byte
	var commit1 commit1Message
	tradeOfNode:=TradeSet[nodeSeq][round%5]
	data,_:=json.Marshal(tradeOfNode)
	tradeHash:=sha256.Sum256(data)
	hash:=getPrepare2Mes(*prepare2Verified)
	if hash!=h&&hash==tradeHash{
		getTradeResult(nodeSeq,round)
		tradeOfNode=TradeSet[nodeSeq][round%5]
		data,_:=json.Marshal(tradeOfNode)
		tradeHash=sha256.Sum256(data)
		commit1.tradeHash=tradeHash
		//fmt.Println(tradeHash)
	}else {
		fmt.Println("节点%d commit1阶段出错\n",nodeSeq)
	}
	return commit1
}

func getTradeResult(nodeSeq int,round int){
	for i:=0;i<K*TradeSize;i++{
		if TradeSet[nodeSeq][round%5][i].Sender!=""{
			TradeSet[nodeSeq][round%5][i].Result=TradeSet[nodeSeq][round%5][i].Remainder-TradeSet[nodeSeq][round%5][i].Send
		}
	}
}

func getPrepare2Mes(prepare2Verified [K]prepare2Message)[32]byte{
	var tradeHash [32]byte
	var h [32]byte
	result:=true
	if prepare2Verified[0].tradeHash!=h{
		for i:=0;i<1;i++{//N/3+1
			prepare1:=prepare2Verified[0].T24Set1[i]
			var data=make([][]byte,2)
			data[0],_=json.Marshal(prepare1.prepare1)
			data[1],_=json.Marshal(prepare1.commit1)
			b:=bytes.Join(data,[]byte(""))
			res:=function.VerifySignHash(sha256.Sum256(b),prepare1.sign,prepare1.nodeSeq)
			if !res&&prepare2Verified[0].tradeHash==prepare1.prepare1.tradeHash{
				result=false
				break
			}
		}
	}else {
		result=false
	}
	if result{
		tradeHash=prepare2Verified[0].tradeHash
		for i:=0;i<K;i++{
			if prepare2Verified[i].tradeHash!=tradeHash{
				fmt.Printf("有主节点%d是拜占庭节点\n",prepare2Verified[i].priSeq)
			}
		}
	}
	return tradeHash
}
